package com.our.base.easylog.event;

import com.our.base.easylog.IPushLog;
import com.our.base.easylog.buffer.cache.CachePool;
import com.our.base.easylog.config.EasyLogProperties;
import com.our.base.easylog.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author wuyang
 * @Description springboot 启动成功的监听器
 * @date 2023/12/8
 **/
@Component
@Slf4j(topic = "easy-log")
public class StartupApplicationListener implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware {
    IPushLog pushLog;
    EasyLogProperties easyLogProperties;
    CachePool cachePool = CachePool.getCachePool();
    private ApplicationContext applicationContext;

    @SuppressWarnings("InfiniteLoopStatement")
    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        SpringUtils.startSpring();
        easyLogProperties = applicationContext.getBean(EasyLogProperties.class);
        pushLog = applicationContext.getBean(IPushLog.class);
        if (!easyLogProperties.isEnable()) {
            return;
        }
        log.info("日志推送服务启动。");
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        // 定时任务，到最大等待时间推送一次
        executorService.scheduleAtFixedRate(() -> {
            if (SpringUtils.getSpringStatus() == 1 && cachePool.getSize() > 0) {
                pushLog.pushLog();

            }
        }, 0, easyLogProperties.getMaxWaitTime(), TimeUnit.SECONDS);
        //启动一个线程，判断缓存池里面是否已经满了，满了就推送。
        executorService.execute(() -> {

            while (true) {
                if (cachePool.getSize() >= easyLogProperties.getMaxCache()) {
                    try {
                        pushLog.pushLog();
                        Thread.sleep(100);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                }

            }
        });


    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
